package main

import (
	"fmt"
	"github.com/disintegration/imaging"
	"log"
	"path/filepath"
	"time"
)

// 图片裁剪
func imgResize(target, source string) {
	srcImage, err := imaging.Open(source)
	if err != nil {
		log.Fatalf("failed to open image: %v", err)
	}
	// Resize srcImage to size = 128x128px using the Lanczos filter.
	dstImage128 := imaging.Resize(srcImage, 128, 128, imaging.Lanczos)
	srcImage.Bounds()
	err = imaging.Save(dstImage128, target)
	if err != nil {
		log.Fatalf("failed to Save image: %v", err)
	}
}

func makeThumbnails(filenames []string) {
	start := time.Now()
	for _, f := range filenames {
		ext := filepath.Ext(f)
		filePrefix := f[0 : len(f)-len(ext)]
		newFileName := fmt.Sprintf("%s-128x128px.%s", filePrefix, ext)
		imgResize(newFileName, f)
	}
	take := time.Now().Sub(start).Milliseconds()
	fmt.Printf("makeThumbnails 耗时: %d 耗时 \n", take)
}

func makeThumbnails2(filenames []string) {
	start := time.Now()
	ch := make(chan struct{})
	for _, f := range filenames {
		go func(f string) {
			ext := filepath.Ext(f)
			filePrefix := f[0 : len(f)-len(ext)]
			newFileName := fmt.Sprintf("%s.128-128.%s", filePrefix, ext)
			imgResize(f, newFileName)
			ch <- struct{}{}
		}(f)
	}
	take := time.Now().Sub(start).Milliseconds()
	fmt.Printf("makeThumbnails2 耗时: %d 耗时 \n", take)
}

func main() {
	strs := []string{"avatar.jpg", "16sucai.jpg", "upaiyun.jpg"}

	// makeThumbnails(strs)

	makeThumbnails2(strs)

}
